#include "qudpsender.h"
#include "ui_qudpsender.h"
QUdpSender::QUdpSender(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QUdpSender)
{
    ui->setupUi(this);
    ui->textEditShow->setReadOnly(true);
    qUdpSocket = new QUdpSocket(this);

    on_rebindButton_clicked();
}

QUdpSender::~QUdpSender()
{
    delete ui;
}

void QUdpSender::on_sendButton_clicked()
{

    QString sendText = ui->textEditSend->toPlainText();
    if (!sendText.isEmpty()) {
        QString ip = ui->lineEditIp->text();
        int port = ui->lineEditPort->text().toInt();
        qint64 sendSize = qUdpSocket->writeDatagram(sendText.toUtf8(),QHostAddress(ip),port);
        if (sendSize>0) {
            ui->textEditSend->clear();
        }else {
            ui->textEditShow->append(QString("数据发送失败!请检查网络是否畅通!网络配置是否正确"));
        }
    }
}

void QUdpSender::on_rebindButton_clicked()
{
    //如果当前套接字不是未连接状态，则先关闭套接字才能重新绑定端口成功
    if (qUdpSocket->state()!=QAbstractSocket::UnconnectedState) {
        quint16 localPort = qUdpSocket->localPort();
        if (localPort) {
            ui->textEditShow->append(QString("端口%1已经解除绑定!").arg(localPort));
        }
        qUdpSocket->close();
    }

    //重新绑定端口
    int bindPort = ui->lineEditBind->text().toInt();
    bool isBindOk = qUdpSocket->bind( bindPort);
    //组播时需要指定AnyIPv4,不能绑定AnyIPv6或Any
    //    bool isBindOk = qUdpSocket->bind(QHostAddress::AnyIPv4, bindPort);

    if (isBindOk) {
        //加入组播和退出组播
        //qUdpSocket->joinMulticastGroup(QHostAddress("224.0.0.2"));
        //qUdpSocket->leaveMulticastGroup(QHostAddress("224.0.0.2"));
        this->setWindowTitle(QString("UDP端口%1 - 可以启动多个程序测试").arg(bindPort));
        if (bindPort>65535) {
            ui->textEditShow->append(QString("端口最大值为65535!"));
        }
        ui->textEditShow->append(QString("端口%1绑定成功!").arg(qUdpSocket->localPort()));
        if (conn) {
            QObject::disconnect(conn);
        }
        conn = connect(qUdpSocket,&QUdpSocket::readyRead,
                       [=](){
            QHostAddress hostAddress;
            quint16 port;
            char buf[1024]={0};
            quint64 readSize =  qUdpSocket->readDatagram(buf,sizeof buf,&hostAddress,&port);
            if (readSize==-1) {
                ui->textEditShow->append(QString("%1:%2内容读取错误!请检查网络配置是否正确!")
                                         .arg(hostAddress.toString())
                                         .arg(port));
            }else {
                QString readText = QString("%1:%2:%3")
                        .arg(hostAddress.toString())
                        .arg(port)
                        .arg(buf);
                ui->textEditShow->append(readText);
            }
        });
    }else {
        ui->textEditShow->append(QString("端口%1绑定失败!").arg(bindPort));
        this->setWindowTitle(QString("UDP发送测试! "));
    }
}

void QUdpSender::on_clearButton_clicked()
{
    ui->textEditShow->clear();
}
